package com.hcss.core.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hcss.core.util.SysDictionary;



public class LoginFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException,
                                                                                          ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String url = request.getRequestURI();
        String contextPath = request.getContextPath();
        if (!url.matches("^(.+[.])(jsp|png|gif|jpg|js|css|jspx|jpeg|html|xls|woff|tff|xlsx|gzjs|gzcss|pdf|swf|ico)$")
        		&&!url.contains("/userInfoManage/")) {
            Object obj = request.getSession().getAttribute(SysDictionary.LOGIN_USERINFO);
            if (null == obj) {
                if (url.equals(contextPath + "/")) {
                    response.sendRedirect(contextPath + "/userInfoManage/loginToPage");
                } else {
                    PrintWriter out = response.getWriter();
                    String loginPage = contextPath + "/userInfoManage/loginToPage";
                    StringBuffer sb = new StringBuffer();
                    sb.append("<script type=\"text/javascript\">");
                    sb.append("window.top.location.href='");
                    sb.append(loginPage);
                    sb.append("';");
                    sb.append("</script>");
                    out.print(sb.toString());
                    out.flush();
                }
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}
